package com.zty.xiaomi.server.Controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.easysdk.factory.Factory;
import com.zty.xiaomi.server.Config.AlipayConfig;
import com.zty.xiaomi.server.Mapper.Order;
import com.zty.xiaomi.server.Service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/alipay")
public class AliPayController {
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Order order;



    /**
     * 跳转到支付界面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/page")
    public String pay(String subject, String total) throws Exception {
        return alipayService.toPayPage(subject, "10011", total);
    }

    /**
     * @param request: 请求
     * @return java.lang.String
     * @description: 支付宝异步回调
     */
    @RequestMapping("/notify")
    public String notify_url(HttpServletRequest request) throws Exception {

        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            // 支付宝验签
//            if (Factory.Payment.Common().verifyNotify(params)) {
            // 验签通过
            System.out.println("交易名称: " + params.get("subject"));
            System.out.println("交易状态: " + params.get("trade_status"));
            System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
            System.out.println("商户订单号: " + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
            System.out.println("买家付款时间: " + params.get("gmt_payment"));
            System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
            int out_trade_no = Integer.parseInt(params.get("out_trade_no"));
            String trade_no=params.get("trade_no");
            order.updOrderTime(out_trade_no, params.get("gmt_payment"));
            order.buyOrder(out_trade_no,trade_no);
            redisTemplate.delete(params.get("out_trade_no")+"Tobepaid");
//            redisTemplate.opsForValue().set(params.get("out_trade_no")+"Forthegoods","",5, TimeUnit.MINUTES);
//            }
        }
        return "success";
    }


    public ModelAndView toRefund(String alipayNum, double money) throws IOException {
        ModelAndView mv=new ModelAndView();
        AlipayConfig alipayConfig = new AlipayConfig();
        // 设置编码格式
//        response.setContentType("text/html;charset=utf-8");
//        PrintWriter out = response.getWriter();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.gatewayUrl, alipayConfig.app_id,
                alipayConfig.merchant_private_key, "json", alipayConfig.charset, alipayConfig.alipay_public_key, alipayConfig.sign_type);
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        //商户订单号，必填
        String out_trade_no = "";
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = "";
        //标识一次退款请求，同一笔交易多次退款需要保证唯一。如需部分退款，则此参数必传；不传该参数则代表全额退款
        String out_request_no = new String(UUID.randomUUID().toString());
        // 字符转义很重要
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"refund_amount\":\"" + refund_amount + "\","
                + "\"out_request_no\":\"" + out_request_no + "\"}");
        //请求
        AlipayTradeRefundResponse result = null;
        try {
            result = alipayClient.execute(alipayRequest);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if (result.isSuccess()) {
            System.out.println("退款成功");
            mv.setViewName("redirect:/myOrder");
        }else {
            System.out.println("退款失败");
            mv.setViewName("error");
        }
        return mv;
    }

}
